<?php 
/**
*@author renchengli
*/

//连接数据库,采用到单例模式,

class Mysql extends db{
	private static $ins=null;
	private $conn=null;
	private $conf='';

	public function __construct(){
		$this->conf=Conf::getIns();
		$this->connect($this->conf->host,$this->conf->user,$this->conf->pwd);
		$this->selectdb($this->conf->db);
		$this->setcharset($this->conf->charset);
	}
	//接口
	static public function getIns(){
		if(self::$ins instanceof self){
			return self::$ins;
		}else{
			self::$ins=new Mysql();
			return self::$ins;
		}
	}
	//连接数据库
	public function connect($h,$u,$p){
		@$this->conn=mysql_connect($h,$u,$p);
		if(!$this->conn){
			$err=new Exception('连接错误');
			throw $err;
		}
	}
	//发送数据
	public function query($sql){
		$rs=mysql_query($sql,$this->conn);
		log::write($sql);
		return $rs;
	}
	//选库
	public function selectdb($db){
		$sql="use $db";
		$this->query($sql);
	}
	//设字符集
	public function setcharset($charset){
		$sql="set names $charset";
		$this->query($sql);
	}
	//获取所有数据
	public function getAll($sql){
		$rs=$this->query($sql);
		$data=array();
		while($row=mysql_fetch_assoc($rs)){
			$data[]=$row;
		}
		return $data;
		
	}
	//获取一行数据
	public function getRow($sql){
		$rs=$this->query($sql);
		return mysql_fetch_row($rs);
	}
	//获取一个数据
	public function getOne($sql){
		$rs=$this->query($sql);
		$row=mysql_fetch_row($rs);
		return $row[0];
	}
	//增,改自动拼接语句
	public function autoExecute($table,$data,$act='insert',$where=1){
		if(empty($data)){
			return false;
		}
		if($act=='insert'){
			//insert into table (a,b,c) values ('a','b','c');
			$sql="insert into $table (" . implode(',',array_keys($data)) . ") values ('";
			$sql .=implode("','",array_values($data)) . "')";
			return $this->query($sql);
		}else if($act=='update'){
			//update table set a='a',b='b' where id=1;
			$sql="update $table set ";
			foreach($data as $k=>$v){
				$sql .=$k . "='" . $v . "',";
			}
			$sql=rtrim($sql,',') . ' where ' .$where;
			return $this->query($sql);
		}
	}
	//获取上一次操作所产生的ID
	public function getLastId(){
		return mysql_insert_id();
	}
	//获取上一次操作所影响的行数
	public function affectRows(){
		return mysql_affected_rows();
	}

}



?>